/*
 * Copyright (c) [2021] Zhang Yansen.All rights reserved.
 *
 * js-export-file is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

/**
 * 获取 query string
 * @param {*} params 
 * @returns string
 */
function getQueryString(params) {
  if (!params) return ;

  const keys = Object.keys(params)
  const arr = keys.map((key) => {
    const val = params[key]
    if (val === null || val === undefined) return false;

    return `${key}=${encodeURIComponent(val)}`
  })

  // eslint-disable-next-line consistent-return
  return arr.filter(Boolean).join('&')
}

/**
 * 获取 url 对应的 blob 数据
 * 请求参数与 fetch 标准相似
 * @param {*} url 请求地址
 * @param {*} opt 请求参数
 * @returns 
 */
export function fetchBlob(url, opt) {
  const { params, ...initArgs } = opt || {}
  const resource = params ? `${url}?${getQueryString(params)}` : url

  return fetch(resource, initArgs).then(response => response.blob())
}

/**
 * 导出 blob 文件
 * @param {*} fileName 文件名
 * @param {*} blob 内容
 */
export function exportBlob(fileName, blob) {
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', fileName);
  link.click();
  URL.revokeObjectURL(url);
}

/**
 * 导出 url 文件
 * @param {*} fileName 文件名
 * @param {*} url 请求地址
 * @param {*} opt 请求参数 与 fetch 标准相似
 * @returns 
 */
export function exportUrl(fileName, url, opt) {
  return fetchBlob(url, opt).then(blob => exportBlob(fileName, blob))
};
